package com.enterprise.support.utility.generator.panel;

import com.enterprise.support.utility.generator.pub.GeneratorConfig;
import com.enterprise.application.swing.jeta.AbstractPanel;
import com.enterprise.support.utility.Enterprise;
import com.enterprise.support.utility.SwingUtility;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2011-1-26
 * Time: 13:45:29
 * To change this template use File | Settings | File Templates.
 */
public class JdbcConfigPanel extends AbstractPanel implements ItemListener {
    private static Vector dbType = new Vector() {{
        add(" MySql ");
        add(" SqlServer ");
        add(" SqlServer2008 ");
        add(" Oracle8 ");
        add(" Oracle9 ");
        add(" Oracle10 ");
    }};
    private static Map<String, String[]> dbConfigs = new HashMap() {{
        put("MySql", new String[]{
                "com.mysql.jdbc.Driver",
                "jdbc:mysql://{HOST}:{PORT}/{DBNAME}", "3306",
                "org.hibernate.dialect.MySQLDialect"
        });
        put("SqlServer", new String[]{
                "net.sourceforge.jtds.jdbc.Driver",
                "jdbc:jtds:sqlserver://{HOST}:{PORT}/{DBNAME}", "1433",
                "org.hibernate.dialect.SQLServerDialect"
        });
        put("SqlServer2008", new String[]{
                "net.sourceforge.jtds.jdbc.Driver",
                "jdbc:jtds:sqlserver://{HOST}:{PORT}/{DBNAME}", "1433",
                "org.hibernate.dialect.SQLServer2008Dialect"
        });
        put("Oracle8", new String[]{
                "oracle.jdbc.driver.OracleDriver",
                "jdbc:oracle:thin:@{HOST}:{PORT}:{DBNAME}", "1521",
                "org.hibernate.dialect.Oracle8iDialect"
        });
        put("Oracle9", new String[]{
                "oracle.jdbc.driver.OracleDriver",
                "jdbc:oracle:thin:@{HOST}:{PORT}:{DBNAME}", "1521",
                "org.hibernate.dialect.Oracle9iDialect"
        });
        put("Oracle10", new String[]{
                "oracle.jdbc.driver.OracleDriver",
                "jdbc:oracle:thin:@{HOST}:{PORT}:{DBNAME}", "1521",
                "org.hibernate.dialect.Oracle10gDialect"
        });
    }};

    public JdbcConfigPanel() {
        super("com\\enterprise\\support\\utility\\generator\\panel\\JdbcConfigPanel.xml");
    }

    public void initComponents() {
        Enterprise properties = new Enterprise(GeneratorConfig.getProperties(GeneratorConfig.jdbcProperties));
        if (!GeneratorConfig.jdbcProperties.exists() || properties.isEmpty()) {
            properties.putAll(com.enterprise.support.utility.Configuration.getProperties("/config/jdbc.properties"));
        }

        JComboBox combox = super.mainPanel.getComboBox("dbtype");
        combox.setModel(new DefaultComboBoxModel(dbType));
        combox.setSelectedItem(properties.getString("dbpool.dbtype"));

        itemStateChanged(new ItemEvent(combox, 0, combox.getSelectedItem(), 1));
        super.mainPanel.getTextField("host").setText(properties.getString("dbpool.jdbcHost"));
        super.mainPanel.getTextField("port").setText(properties.getString("dbpool.jdbcPort"));
        super.mainPanel.getTextField("dbname").setText(properties.getString("dbpool.jdbcDbName"));

        super.mainPanel.getTextField("username").setText(properties.getString("dbpool.user"));
        super.mainPanel.getTextField("password").setText(properties.getString("dbpool.password"));

        super.mainPanel.getTextField("annotatedclasspath").setText(properties.getString("hibernate.annotatedClassesLocations"));
        super.mainPanel.getComboBox("showsql").setModel(new DefaultComboBoxModel(new Vector<Object>() {{
            add(" Yes");
            add(" No");
        }}));
        super.mainPanel.getComboBox("showsql").setSelectedIndex(properties.getBoolean("hibernate.show_sql") ? 0 : 1);

        super.mainPanel.getComboBox("hbm2ddl").setModel(new DefaultComboBoxModel(new Vector<Object>() {{
            add(" Yes");
            add(" No");
        }}));
        super.mainPanel.getComboBox("hbm2ddl").setSelectedItem(properties.equals("hibernate.hbm2ddl.auto", "update") ? " Yes" : " No");

    }

    public void itemStateChanged(ItemEvent event) {
        if (event.getStateChange() == 1) {
            String[] propertys = dbConfigs.get(String.valueOf(event.getItem()).trim());
            propertys = propertys == null ? dbConfigs.get("MySql") : propertys;
            mainPanel.getTextField("dialect").setText(propertys[3]);
        }
    }

    public void addListeners() {
        super.mainPanel.getComboBox("dbtype").addItemListener(this);
        super.mainPanel.getButton("submit").addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Enterprise input = getInput();
                if (input.isEmpty("dbtype")) {
                    SwingUtility.warning("DbType(数据库类型) 为必选！");
                } else if (input.isEmpty("host")) {
                    SwingUtility.warning("Host(服务器地址) 为必填！");
                } else if (input.getString("host").indexOf(":") != -1) {
                    SwingUtility.warning("Host(服务器地址) 不要包含端口！");
                } else if (!input.isEmpty("port") && !input.getString("port").matches("\\d+")) {
                    SwingUtility.warning("Port(端口) 必须为数字！");
                } else if (input.isEmpty("dbname")) {
                    SwingUtility.warning("DbName(数据库名称) 为必填！");
                } else if (input.isEmpty("username")) {
                    SwingUtility.warning("Username(用户名) 为必填！");
                } else if (input.isEmpty("password")) {
                    SwingUtility.warning("Password(密码) 为必填！");
                } else if (input.isEmpty("annotatedclasspath")) {
                    SwingUtility.warning("Annotatedclasspath(Hibernate实体对象存放路径) 为必填！");
                } else {

                    Properties properties = GeneratorConfig.getProperties(GeneratorConfig.jdbcProperties);
                    if (!GeneratorConfig.jdbcProperties.exists() || properties.isEmpty()) {
                        properties.putAll(com.enterprise.support.utility.Configuration.getProperties("/config/jdbc.properties"));
                    }

                    String[] propertys = dbConfigs.get(input.getString("dbtype").trim());
                    properties.put("dbpool.dbtype", input.getString("dbtype"));
                    properties.put("dbpool.driverClass", propertys[0]);
                    properties.put("dbpool.jdbcUrl", propertys[1]
                            .replace("{HOST}", input.getString("host"))
                            .replace("{PORT}", input.isEmpty("port") ? propertys[2] : input.getString("port"))
                            .replace("{DBNAME}", input.getString("dbname")));
                    properties.put("dbpool.user", input.getString("username"));
                    properties.put("dbpool.password", input.getString("password"));
                    properties.put("dbpool.jdbcHost", input.getString("host"));
                    properties.put("dbpool.jdbcPort", input.getString("port"));
                    properties.put("dbpool.jdbcDbName", input.getString("dbname"));

                    properties.put("hibernate.annotatedClassesLocations", input.getString("annotatedclasspath"));
                    if (input.equals("hbm2ddl", " Yes")) {
                        properties.put("hibernate.hbm2ddl.auto", "update");
                    } else {
                        properties.put("hibernate.hbm2ddl.auto", "false");
                    }
                    properties.put("hibernate.dialect", input.getString("dialect"));

                    properties.put("hibernate.show_sql", input.equals("showsql", " Yes") ? "true" : "false");

                    GeneratorConfig.store(GeneratorConfig.jdbcProperties, properties);
                    SwingUtility.info("设置成功！");
                }
            }
        });
    }
}
